<template>
    <div class="policyManage">
        <div style="padding: 0 30px;margin-top: 10px">
            <SearchComponent :searchConfig="searchConfig" @resetFn="reset" @searchFn="queryFn"/>
        </div>

        <div class="content">
            <div class="strategyContent">
                <div style="margin-bottom: 10px;float: right">
                    <el-button v-if="!!btnPermission['PolicyManage-creatNewPolicy']"
                               :disabled="!btnPermission['PolicyManage-creatNewPolicy']" size="small"
                               type="primary"
                               @click="creatNewPolicy">创建新策略
                    </el-button>
                    <!--                    <el-button type="primary" size="small">导出</el-button>-->
                </div>
                <TableComponent v-loading="isLoading" :assetList="strategyList" :height="tableHeight"
                                :tableColumns="tableColumns"
                                element-loading-text="加载中..." @sortChangeFn="sortChangeFn">

                    <template #id="{row}">
                        <span>T{{ row.id }}</span>
                    </template>

                    <template #scFlag>
                        <el-table-column align="left" label="策略类型" prop="scFlag" width="90">
                            <template #default="{ row }">
                                <span v-if="row.scFlag">SC</span>
                                <span v-else>trigger</span>
                            </template>
                        </el-table-column>
                    </template>
                    <template #priority>
                        <el-table-column align="left" prop="priority" sortable="custom" width="120">
                            
                            <template v-slot:header>
                                优先级
                                <el-tooltip class="box-item" effect="light" placement="top-start">
                                    <template #content>
                                        优先级：1-3 【普通】<br/>
                                        优先级：4-7 【高优】<br/>
                                        优先级：8-10【紧急】
                                    </template>
                                    <i class="el-icon-question"></i>
                                </el-tooltip>

                            </template>
                        </el-table-column>
                    </template>

                    <template #status>
                        <el-table-column align="left" label="状态" prop="status" sortable="custom" width="80">
                            <template #default="{ row }">
                                <span v-if="row.status == 0">暂停</span>
                                <span v-if="row.status == 1">启用</span>
                            </template>
                        </el-table-column>
                    </template>

                    <template #operation="{ row }">
                        <el-button v-if="btnPermission['PolicyManage-updateFn']"
                                   :disabled="!btnPermission['PolicyManage-updateFn']" size="small" type="text"
                                   @click="updateFn(row)">更新
                        </el-button>

                        <el-button v-if="btnPermission['PolicyManage-changeStatus']"
                                   :disabled="!btnPermission['PolicyManage-changeStatus']" size="small" type="text"
                                   @click="changeStatus(row)">
                            <span v-if="row.status===0">启用</span>
                            <span v-if="row.status===1">暂停</span>
                        </el-button>

                        <el-popconfirm v-if="btnPermission['PolicyManage-deleteFn']" title="确定要删除吗?"
                                       @confirm='deleteFn(row)'>
                            <template #reference>
                                <el-button :disabled="!btnPermission['PolicyManage-deleteFn']" size="small"
                                           style="color:#f00;"
                                           type="text">删除
                                </el-button>
                            </template>
                        </el-popconfirm>
                        <div v-if="!btnPermission['PolicyManage-deleteFn']&&!btnPermission['PolicyManage-updateFn']">
                            ---
                        </div>
                    </template>
                </TableComponent>
                <el-pagination v-model:page-size="strategyPageData.size" :currentPage="strategyPageData.current"
                               :page-sizes="[10,20, 30, 40, 50]"
                               :total="strategyPageData.total"
                               background layout="total, sizes, prev, pager, next, jumper"
                               style="margin-top: 20px;float: right"
                               @size-change="handleSizeChange" @current-change="strategyPageChange">
                </el-pagination>
            </div>
        </div>

        <PopComponent ref="popComponent"/>

    </div>

</template>

<script>
import TableComponent from '@/components/TableComponent.vue';
import PopComponent from './components/PopComponent.vue';
import {getStrategyApi, policyDeleteApi, policyEditApi} from '@/api/carManage/policyManage.js';
import {searchConfig, tableColumns} from '@/constant/config.js';
import {computed, onMounted, reactive, ref, watch} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {ElMessage} from 'element-plus';
import SearchComponent from '@/components/SearchComponent.vue';
import {useStore} from 'vuex';
import {removeNull, formatPriorityText} from "@/utils/util";

export default {
    components: {
        TableComponent,
        PopComponent,
        SearchComponent,
    },
    setup() {
        const strategyPageData = reactive({
            total: 0,
            current: 1,
            size: 10,
        });

        const isLoading = ref(false);
        const strategyList = ref([]);
        const popComponent = ref(null);
        const filterObj = ref({});
        const store = useStore();
        const btnPermission = computed(() => store.state.btnPermission);


        const queryFn = (para) => {
            if (para.id && para.id.charAt(0) === 'T') {
                para.id = para.id.slice(1);
            }
            filterObj.value = para;
            strategyPageData.current = 1;
            getStrategyList(strategyPageData.size);
        };

        const reset = () => {
            filterObj.value = {};
            strategyPageData.current = 1;
            filterQuery.orderByType = '';
            getStrategyList(strategyPageData.size);
        };

        const filterQuery = reactive({});
        const getStrategyList = (size = 10) => {
            getStrategyApi({
                size: strategyPageData.size,
                current: strategyPageData.current,
                ...removeNull(filterObj.value),
                ...removeNull(filterQuery),
            }).then((res) => {
                if (res.data.code == 200) {
                    let response = res.data.data;
                    strategyList.value = response.records;
                    strategyPageData.total = response.total;
                    strategyPageData.current = response.current;
                }
            });
        };
        const handleSizeChange = (number) => {
            strategyPageData.size = number;
            getStrategyList(number)
        }
        const router = useRouter();
        const creatNewPolicy = () => {
            router.push({
                path: '/triggerConfiguration/CreatePolicy',
                query: {
                    key: +new Date(),
                }
            });
        };

        const updateFn = (row) => {
            sessionStorage.setItem('policyRowData', JSON.stringify(row));

            router.push({
                name: 'UpdatePolicy',
                query: {
                    key: +new Date(),
                }
            });
        };

        const changeStatus = (row) => {

            let editor = JSON.parse(localStorage.getItem('userInfo'))?.employeeId;

            policyEditApi({
                id: row.id,
                modifyBy: editor,
                status: row.status === 0 ? 1 : 0
            }).then(res => {

                getStrategyList();
            })
        }
        const deleteFn = (row) => {
            let modifyBy = JSON.parse(localStorage.getItem('userInfo')).employeeId;
            policyDeleteApi({
                id: row.id,
                modifyBy: modifyBy
            }).then((res) => {
                if (res.data.data == 1) {
                    ElMessage({
                        message: '删除成功',
                        type: 'success',
                    });
                    getStrategyList();
                } else {
                    ElMessage({
                        message: '删除失败',
                        type: 'error',
                    });
                }
            });
        };
        const tableHeight = ref();
        // tableHeight.value = document.body.clientHeight - 70 - 50 - 62 - 60 - 100;
        onMounted(() => {
            // window.addEventListener('resize', () => {
            //     tableHeight.value = document.body.clientHeight - 70 - 50 - 62 - 60 - 100;
            // });
            getStrategyList();
        });
        const route = useRoute();
        watch(() => route.query.key, () => {
            reset();
        })

        const sortChangeFn = (column, prop, order) => {

            if (order === 'ascending') {
                if (prop === 'status') {
                    filterQuery.orderByType = 3;
                } else if (prop === 'priority') {
                    filterQuery.orderByType = 1;
                }
            } else if (order === 'descending') {
                if (prop === 'status') {
                    filterQuery.orderByType = 4;
                } else if (prop === 'priority') {
                    filterQuery.orderByType = 2;
                }
            } else {
                filterQuery.orderByType = '';
            }
            getStrategyList();
        };

        const strategyPageChange = (val) => {
            strategyPageData.current = val;
            getStrategyList(strategyPageData.size);
        };
        return {
            tableColumns,
            strategyList,
            isLoading,
            strategyPageData,
            getStrategyList,
            updateFn,
            deleteFn,
            changeStatus,
            popComponent,
            strategyPageChange,
            creatNewPolicy,
            searchConfig,
            queryFn,
            reset,
            filterObj,
            sortChangeFn,
            filterQuery,
            btnPermission,
            tableHeight,
            handleSizeChange,
            formatPriorityText
        };
    },
};
</script>


<style lang="less" scoped>
.policyManage {
    //background: #eeeeee;
    min-height: 100%;

    .content {
        padding: 10px 20px;
        //padding-bottom: 100px;
        .strategyContent {
            background: #ffffff;
            padding: 10px 20px;
        }

        .policyGroupContent {
            margin-top: 20px;
            background: #ffffff;
            padding: 10px 20px;
            padding-bottom: 100px;
        }
    }
}
</style>
